package com.yugao.fintech.antelope.gateway.service;

import com.alibaba.fastjson2.JSON;
import com.yugao.fintech.antelope.gateway.body.GatewayContext;
import com.yugao.fintech.antelope.base.model.constants.RequestCons;
import com.yugao.fintech.antelope.system.RemoteSystemService;
import com.yugao.fintech.antelope.system.constants.CacheCons;
import com.yugao.fintech.antelope.system.model.rqrs.accesskey.AccessKeyResp;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import com.yugao.fintech.framework.cache.core.service.CacheService;
import com.yugao.fintech.framework.core.response.Resp;
import com.yugao.fintech.framework.core.response.RetOps;
import com.yugao.fintech.framework.core.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class AccessKeyService {
    @Autowired
    private CacheService cacheService;

    @Autowired(name = "myThreadPool")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public AccessKeyResp getAccessKeyBySecretId(String secretId, GatewayContext context) {
        AccessKeyResp accessKeyResp = null;
        try {
            String cacheKey = String.format(CacheCons.ACCESS_KEY, secretId);
            Object obj = cacheService.opsForValue().get(cacheKey);
            if (Objects.isNull(obj)) {
                RemoteSystemService remoteAdminService = SpringUtils.getBean(RemoteSystemService.class);
                //异步调用feign服务接口 　　
                CompletableFuture<Resp<AccessKeyResp>> f = CompletableFuture.supplyAsync(()->
                        remoteAdminService.getAccessKeyBySecretId(secretId), threadPoolTaskExecutor);
                Resp<AccessKeyResp> resp = f.get();
                RetOps.of(resp).assertSuccess(e -> new BizException(e.getCode(), e.getMsg()))
                        .assertDataNotNull(e -> new BizException("密钥不存在"));
                accessKeyResp = resp.getData();
                if (Objects.isNull(accessKeyResp)) {
                    return null;
                }
                cacheService.opsForValue().setEx(cacheKey, JSON.toJSONString(accessKeyResp), 6, TimeUnit.HOURS);
            } else {
                accessKeyResp = JSON.parseObject(String.valueOf(obj), AccessKeyResp.class);
            }
            return accessKeyResp;

        } catch (Exception e) {
            log.error("调用accessKeyApi失败, ", e);
            throw new BizException("远程服务调用失败");
        } finally {
            if (Objects.nonNull(accessKeyResp)) {
                context.addRequestHeader(RequestCons.Headers.ACCESS_SECRET_ID, accessKeyResp.getSecretId());
                context.addRequestHeader(RequestCons.Headers.ACCESS_SECRET_KEY, accessKeyResp.getSecretKey());
            }
        }
    }
}
